import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import Home from "@/views/Home/Home.vue";
import Index from "@/views/Index/index.vue";
import type { App } from "vue";
import { useUserState } from "@/store/user";
import * as http from "@/views/Login/api/http";
import { ElMessage } from "element-plus";

const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    name: "login",
    component: () => import("../views/Login/Login.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 路由前置狗子
router.beforeEach(async (to, form, next) => {
  //   console.log("路由前置", to, form);
  let token = localStorage.getItem("token");
  // 判断用户是否登录,未登录直接跳转登录页面，打断代码往下进行
  if (!token && to.name != "login") {
    ElMessage.warning("请先登录!");
    return next("/login");
  }
  let userState = useUserState();

  // 用户登录且仓库中的数据为空的时候发送请求
  if (token && userState.menus!.length === 0) {
    let adminData = await http.admin.AdminInfo();
    if (adminData.code === 200) {
      // 请求成功将数据存进仓库
      userState.updatedMenus(adminData.data);
      //   动态创建路由地址
      const menusRoutes = userState.getMenusRoutes;
      Object.values(menusRoutes!).forEach((item) => {
        // 一级路由
        let routesobj: RouteRecordRaw = {
          path: `/${item.name}`,
          name: item.name,
          component: Home,
          children: [],
        };
        // 二级路由
        item.children!.forEach((citem) => {
          //   创建子路由
          routesobj.children!.push({
            path: citem.name,
            name: citem.name,
            component: () => import(`../views/${item.name}/${citem.name}.vue`),
          });
        });
        router.addRoute(routesobj);
      });
      router.addRoute({
        path: "/",
        name: "home",
        component: Home,
        redirect: "/index",
        children: [{ path: "/index", component: Index }],
      });
      return next(to.fullPath); //使用了动态路由，需要手动的导航。
      // 打断后面代码进程
      return next();
    } else {
      ElMessage.error("会话失效,请重新登录!");
      // 请求失败，删除token并且跳转登录页面重新登录
      localStorage.removeItem("token");
      // 打断后面代码的进程
      return next("/login");
    }
  } else if (token && to.name === "login" && userState.menus!.length != 0) {
    // 已经登录并且没有进行退出登录，不允许进入登录页面
    ElMessage.warning("请先退出登录!");
    next(form.fullPath);
  } else {
    next();
  }
});

// 优化路由初始化
export function initRouter(app: App<Element>) {
  app.use(router);
}

export default router;
